package br.urca.util;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class CryptDoc {
	
	static byte[] raw = new byte[]{'#', '@', ',', '.', 'U', 'r', 'C', '@', 'W', 'e', 'B', 's', '&', 'r', 'v', 'R'};

	static SecureRandom rnd = new SecureRandom();

	static IvParameterSpec iv = new IvParameterSpec(rnd.generateSeed(16));
	
	public static void main(String[] args) {
		String encrypt = encrypt("A=20101107641,D=12,M=12,Y=2014,T=1");
	    System.out.println("decrypted value:" + (decrypt("#@,.UrCaWeBsErvR", encrypt)));
	}
	
	public static String encrypt(String value) {
	    try {

	        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
	        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
	        cipher.init(Cipher.ENCRYPT_MODE, skeySpec,iv);
	        byte[] encrypted = cipher.doFinal(value.getBytes());
	        System.out.println("encrypted string:" + Base64.encodeBase64String(encrypted));
	        return Base64.encodeBase64String(encrypted);
	    } catch (Exception ex) {
	        ex.printStackTrace();
	    }
	    return null;
	}
	
	public static String decrypt(String key, String encrypted) {
	    try {
	        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");
	        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
	        cipher.init(Cipher.DECRYPT_MODE, skeySpec,iv);
	        byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));

	        return new String(original);
	    } catch (Exception ex) {
	        ex.printStackTrace();
	    }
	    return null;
	}

}
